const fs = require('fs')
const path = require('path')
const moment = require('moment')
const mkdirp = require('mkdirp')

const Controller = require('egg').Controller

class UploadController extends Controller {
  async upload() {
    const { ctx } = this
    const file = ctx.request.files[0]
    let uploadDir = ''

    try {
      let f = fs.readFileSync(file.filepath)
      let d = moment(new Date()).format('YYYYMMDD')
      let dir = path.join(this.config.uploadDir, d)
      await mkdirp(dir)

      let date = Date.now()
      uploadDir = path.join(dir, date + path.extname(file.filename))

      fs.writeFileSync(uploadDir, f)
    } catch (error) {
      console.log('upload file', error)
    } finally {
      ctx.cleanupRequestFiles()
    }

    ctx.body = {
      code: 200,
      msg: '上传成功',
      data: {
        path: uploadDir.replace(/app/g, ''),
      },
    }
  }
}

module.exports = UploadController
